package com.example.weather.old;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.weather.R;
import com.example.weather.old.adapter.WeatherAdapter;
import com.example.weather.old.bean.DailyForecast;
import com.example.weather.old.bean.HeWeather6;
import com.example.weather.old.bean.Weather;
import com.example.weather.utils.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity  implements View.OnClickListener{
    private final static String WEATHER_URL = "https://free-api.heweather.com/s6/weather/forecast";
    private final static String IMAGE_URL = "https://sjbz-fd.zol-img.com.cn/t_s320x510c5/g5/M00/0F/09/ChMkJlfJQWSIIEmVAAQzGYKI3fwAAU7cwLGCn8ABDMx195.jpg";
    private final static String APP_KEY = "75d0df8b260944c2af82ad915b454c88";

    private final static int TYPE_WEATHER = 1;
    private final static int TYPE_IMAGE = 2;

    private LinearLayout mainLayout;
    private RecyclerView rvWeather;

    private List<DailyForecast> forecasts;
    private WeatherAdapter adapter;

    private final Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TYPE_WEATHER:
                    parseJsonByGson((String) msg.obj);
                    break;
                case TYPE_IMAGE:
                    mainLayout.setBackground(new BitmapDrawable(getResources(), (Bitmap) msg.obj));
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        forecasts = new ArrayList<>();
        initView();
        loadBackgroundImage(IMAGE_URL);
    }

    private void initView() {
        rvWeather = findViewById(R.id.rv_weather);
        mainLayout = findViewById(R.id.main_layout);

        findViewById(R.id.btn_weather).setOnClickListener(this);

        adapter = new WeatherAdapter(forecasts);
        rvWeather.setLayoutManager(new LinearLayoutManager(this));
        rvWeather.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        rvWeather.setAdapter(adapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_weather:
                getWeatherByOkHttp("南京");
                break;
        }
    }

    private void getImage(String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = HttpUtil.getConnection(url);
                try {
                    InputStream is = connection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    Message msg = Message.obtain();
                    msg.what = TYPE_IMAGE;
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getImageByOkHttp(String url) {
        Request request = new Request.Builder().url(url).build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try (Response response = new OkHttpClient().newCall(request).execute()) {
                    if (response.isSuccessful()) {
                        Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                        Message msg = Message.obtain();
                        msg.what = TYPE_IMAGE;
                        msg.obj = bitmap;
                        handler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

//        new OkHttpClient().newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(@NotNull Call call, @NotNull IOException e) {
//            }
//
//            @Override
//            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    Bitmap bitmap = BitmapFactory.decodeStream(response.body().byteStream());
//                    Message msg = Message.obtain();
//                    msg.what = TYPE_IMAGE;
//                    msg.obj = bitmap;
//                    handler.sendMessage(msg);
//                }
//            }
//        });
    }

    private void loadBackgroundImage(String url) {
        Glide.with(WeatherActivity.this)
                .asBitmap()
                .load(url)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource,
                                                @Nullable Transition<? super Bitmap> transition) {
                        final Drawable drawable = new BitmapDrawable(getResources(), resource);
                        mainLayout.setBackground(drawable);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    private void getWeather(String location) {
        final String param = "key=" + APP_KEY + "&location=" + location;
        final StringBuilder builder = new StringBuilder();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpURLConnection connection = HttpUtil.getConnection(WEATHER_URL);
                    connection.setDoOutput(true);
                    connection.setRequestMethod("POST");
                    PrintWriter writer = new PrintWriter(connection.getOutputStream());
                    writer.print(param);
                    writer.flush();

                    InputStream is = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String line = null;

                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }

                    Message msg = Message.obtain();
                    msg.what = TYPE_WEATHER;
                    msg.obj = builder.toString();
                    handler.sendMessage(msg);

                    reader.close();
                    is.close();

                    Log.d("MainActivity", builder.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getWeatherByOkHttp(String location) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                RequestBody formBody = new FormBody.Builder()
                        .add("key", APP_KEY)
                        .add("location", location)
                        .build();

                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(WEATHER_URL)
                        .post(formBody)
                        .build();
                try (Response response = client.newCall(request).execute()) {
                    if (response.isSuccessful()) {
                        Message msg = Message.obtain();
                        msg.what = TYPE_WEATHER;
                        msg.obj = response.body().string();
                        handler.sendMessage(msg);

                        Log.d("MainActivity", msg.obj.toString());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJsonByGson(String json) {
        Gson gson = new Gson();
        List<DailyForecast> forecasts = new ArrayList<>();
        JsonObject obj = new JsonParser().parse(json).getAsJsonObject();
        JsonArray array = obj.getAsJsonArray("HeWeather6");
        for (JsonElement element : array) {
            Weather weather = gson.fromJson(element, new TypeToken<Weather>() {
            }.getType());
            forecasts.addAll(weather.getForecasts());
        }
        updateList(forecasts);
    }

    private void updateList(List<DailyForecast> datas) {
        if (this.forecasts.size() > 0) {
            this.forecasts.clear();
        }
        this.forecasts.addAll(datas);
        adapter.notifyDataSetChanged();
    }

    private void parseJsonByFastjson(String json) {
        JSONObject obj = (JSONObject) JSON.parse(json);
        JSONArray array = obj.getJSONArray("HeWeather6");

        List<Weather> weathers = JSON.parseArray(array.toJSONString(), Weather.class);
        if (weathers != null && !weathers.isEmpty()) {
            updateList(weathers.get(0).getForecasts());
        }
    }

    private void parseJsonByMoshi(String json) {
        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<HeWeather6> adapter = moshi.adapter(HeWeather6.class);
        try {
            HeWeather6 heWeather6 = adapter.fromJson(json);
            List<Weather> weathers = heWeather6.getHeWeather6();
            if (weathers != null && !weathers.isEmpty()) {
                updateList(weathers.get(0).getForecasts());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}